#!/bin/bash
export ANDROID_NDK_ROOT=/mnt/android_home/ndk/android-ndk-r28c
# 例如：
# export ANDROID_NDK_ROOT=$HOME/android-ndk-r28c
# 配置
NDK_ROOT=${ANDROID_NDK_ROOT}
API=21
FFMPEG_DIR=/opt/module/src/ffmpeg/n8.1-dev
BUILD_DIR=${FFMPEG_DIR}/build_android
INSTALL_DIR=${FFMPEG_DIR}/dist

# 支持的架构映射
declare -a ABIS=("arm64-v8a" "armeabi-v7a" "x86_64" "x86")
declare -a TARGETS=("aarch64-linux-android" "armv7a-linux-androideabi" "x86_64-linux-android" "i686-linux-android")
declare -a CPUS=("generic" "generic" "generic" "generic")

# 清理旧构建
rm -rf $BUILD_DIR $INSTALL_DIR
TOOLCHAIN=$NDK_ROOT/toolchains/llvm/prebuilt/linux-x86_64
export PATH=$TOOLCHAIN/bin:$PATH
AR=$TOOLCHAIN/bin/llvm-ar
RANLIB=$TOOLCHAIN/bin/llvm-ranlib
STRIP=$TOOLCHAIN/bin/llvm-strip
NM=$TOOLCHAIN/bin/llvm-nm

# 创建输出目录
mkdir -p $INSTALL_DIR

for i in "${!ABIS[@]}"; do
    ABI=${ABIS[i]}
    TARGET=${TARGETS[i]}
    CPU=${CPUS[i]}

    echo "👉 正在编译: $ABI (Target: $TARGET)"


    CC=$TOOLCHAIN/bin/$TARGET$API-clang
    CXX=$TOOLCHAIN/bin/$TARGET$API-clang++



    # 检查编译器是否存在
    if [ ! -f "$CC" ]; then
        echo "❌ 编译器未找到: $CC"
        exit 1
    fi

    # 架构特定参数
    case $ABI in
        "arm64-v8a")
            ARCH="aarch64"
            ;;
        "armeabi-v7a")
            ARCH="arm"
            ;;
        "x86_64")
            ARCH="x86_64"
            ;;
        "x86")
            ARCH="x86"
            ;;
    esac

    # 创建构建目录
    BUILD_ABI_DIR=$BUILD_DIR/$ABI
    INSTALL_ABI_DIR=$INSTALL_DIR/$ABI
    mkdir -p $BUILD_ABI_DIR $INSTALL_ABI_DIR

    cd $BUILD_ABI_DIR

# 在循环内
$FFMPEG_DIR/configure \
    --prefix=$INSTALL_ABI_DIR \
    --enable-cross-compile \
    --target-os=android \
    --arch=$ARCH \
    --cpu=$CPU \
    --cc=$TARGET$API-clang \
    --cxx=$TARGET$API-clang++ \
    --ar=llvm-ar \
    --ranlib=llvm-ranlib \
    --nm=llvm-nm \
    --strip=llvm-strip \
    --sysroot=$NDK_ROOT/sysroot \
    --disable-shared \
    --enable-static \
    --extra-cflags="-Os -fPIC -D__ANDROID_API__=$API" \
    --extra-ldflags="-llog -latomic -lm" \
    --host-cc="gcc" \
    --cross-prefix="" \
    --pkg-config=pkg-config \
    --disable-stripping \
    --disable-ffmpeg \
    --disable-ffprobe \
    --disable-ffplay \
    --disable-runtime-cpudetect

    # 检查 configure 是否成功
    if [ $? -ne 0 ]; then
        echo "❌ configure 失败！查看 ffbuild/config.log"
        exit 1
    fi

    # 编译并安装
    make -j$(nproc) && make install
    if [ $? -ne 0 ]; then
        echo "❌ 编译失败！"
        exit 1
    fi

    make clean
    cd $FFMPEG_DIR
    echo "✅ $ABI 编译完成 → $INSTALL_ABI_DIR"
done

echo "🎉 所有架构编译成功！"
echo "输出目录: $INSTALL_DIR"